package com.sheng.project.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author by ls
 * @date 2023/7/12
 */
@Slf4j
@Component
@ServerEndpoint("/web-socket")
public class WebSocketController {

    /**
     * 前端发送请求建立 websocket 连接，就会执行 @OnOpen 方法<p>
     * 网页在线测试地址：<a href="http://www.websocket-test.com/">www.websocket-test.com</a>
     **/
    @OnOpen
    public void open(Session session) throws IOException, InterruptedException {
        System.out.println(session);
        deal(session);
    }

    private void deal(Session session) throws InterruptedException, IOException {
        new Thread(() -> {
            while (true) {
                try {
                    if (session.isOpen()) {
                        // 执行WebSocket 会话操作
                        TimeUnit.SECONDS.sleep(3);
                        session.getBasicRemote().sendText("3s from server: hello");
                    } else {
                        // 会话已关闭，请处理相关逻辑
                        session.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("退出当前线程");
                    break;
                }
            }
        }).start();
    }


    /**
     * 前端关闭页面或者主动关闭 websocket 连接，都会执行 close
     **/
    @OnClose
    public void close(Session session) throws IOException {
        log.info("close");
        log.info("session: {}", session);
        session.close();
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("get client msg. ID: {}. msg: {}", session.getId(), message);
        session.getBasicRemote().sendText("from server:" + message);
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
}
